package com.android.sreader;

import java.util.ArrayList;
import java.util.List;

import com.android.sreader.utility.Book;
import com.android.sreader.utility.Paragraph;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Layout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Scroller;
import android.widget.TextView;

public class PageScrollLayout extends ViewGroup {
	private static final String TAG = "PageScrollLayout";
	private Scroller mScroller;
	private VelocityTracker mVelocityTracker;
	
	private int mCurScreen;
	private int mDefaultScreen = 0;
	
    public static interface OnPageChange {
        public void onPage(int page);
    }
    
    public void setOnPageChange(OnPageChange onPageChange) {
    	pageChangeListener = onPageChange;
    }
    
    private OnPageChange pageChangeListener = null;
    
    public static interface OnMiddleClick {
    	public void onMinddleClick();
    }
    
    public void setOnMiddleClick(OnMiddleClick onMiddleClick){
    	this.middleClickListener = onMiddleClick;
    }
    
    private OnMiddleClick middleClickListener = null;
	
	private static final int TOUCH_STATE_REST = 0;
	private static final int TOUCH_STATE_SCROLLING = 1;
	
	private static final int SNAP_VELOCITY = 600;
	
	private int mTouchState = TOUCH_STATE_REST;
	private int mTouchSlop;
	private float mLastMotionX;
	private float mLastMotionY;
	
	private int mPageCount = 0;
	private int mLeftHeight = 0;
	private int mMeasuredHeight = 0;
	private int mMeasureWidth   = 0;
	private Context mContext;
	private int widthMeasureSpec, heightMeasureSpec;
	private int mChapterCount = 0;
	private int mCurChapter   = 0;
	private int mCurPage	  = 0;

	public int getCurChapter(){
		return this.mCurChapter;
	}
	
	public int getCurPage(){
		return this.mCurPage;
	}
	public PageScrollLayout(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}

	public PageScrollLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		mScroller = new Scroller(context);
		mContext = context;
		mCurScreen = mDefaultScreen;
		mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
		
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		// TODO Auto-generated method stub
		Log.e(TAG, "onLayout");
		if(!changed) return ;
		
		int childCount = getChildCount();
		int childLeft = 0;
		mLeftHeight = this.mMeasuredHeight;
		LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		for(int i = 0 ; i < childCount; i++){
			final View childView = getChildAt(i);
			final int childWidth = childView.getMeasuredWidth();
			if(childView.getContentDescription() == "text"){
				TextView tv = (TextView)childView;
				final int viewHeight = tv.getLineHeight() * tv.getLineCount();
				if(viewHeight < mLeftHeight){
					childView.layout(childLeft, this.mMeasuredHeight - mLeftHeight,childWidth + childLeft, this.mMeasuredHeight - mLeftHeight +viewHeight);
					mLeftHeight -= (viewHeight + 8);
				}else{
					int lineLeft = mLeftHeight / tv.getLineHeight();
					Layout textViewLayout = tv.getLayout();
					int end = textViewLayout.getLineEnd(lineLeft-1);
					if(end < tv.getText().length()){
						String str1 = (String) tv.getText().subSequence(0, end);
						String str2 = (String) tv.getText().subSequence(end, tv.getText().length());
						TextView tv1 = (TextView) inflater.inflate(R.layout.para_text, null);
						TextView tv2 = (TextView) inflater.inflate(R.layout.para_text, null);
						tv1.setText(str1);
						tv2.setText(str2);
						removeViewAt(i);
						tv1.layout(childLeft, this.mMeasuredHeight - mLeftHeight,childWidth + childLeft, this.mMeasuredHeight);
						this.addView(tv1, i);
						childLeft += childWidth;
						this.mPageCount ++;
						int lineNum = calcLines(str2, tv2.getPaint(), mMeasureWidth);
						tv2.layout(childLeft, 0, childWidth + childLeft, lineNum * tv.getLineHeight());
						this.addView(tv2,i+1);
						mLeftHeight = this.mMeasuredHeight - lineNum * tv.getLineHeight() - 8;
						childCount++;
						i++;
					}else{
						childView.layout(childLeft, this.mMeasuredHeight - mLeftHeight,childWidth + childLeft, this.mMeasuredHeight - mLeftHeight +viewHeight);
						childLeft += childWidth;
						this.mPageCount ++;
						mLeftHeight = this.mMeasuredHeight;
					}
				/*	int lineHeight = tv.getLineHeight();
					List<TextViewDivider> list = this.divideIntoParas(tv, mLeftHeight, this.mMeasureWidth);
					this.removeViewAt(i);
					TextViewDivider tvd = list.get(0);
					tv = tvd.tv;
					tv.layout(childLeft, this.mMeasuredHeight - mLeftHeight, childWidth + childLeft,  this.mMeasuredHeight);
					this.addView(tv,i);
					childLeft += childWidth;
					this.mPageCount++;

					
					for(int j = 1 ; j < list.size()-1 ; j++){
						tvd = list.get(j);
						tv = tvd.tv;
						tv.layout(childLeft, 0, childWidth + childLeft, this.mMeasuredHeight);
						childLeft += childWidth;
						this.mPageCount++;
						childCount++;
						i++;
						this.addView(tv,i);	
					}
					
					tvd = list.get(list.size()-1);
					tv  = tvd.tv;
					tv.layout(childLeft, 0, childWidth + childLeft, tvd.lines * lineHeight);
					this.addView(tv,i);
					childCount++;
					i++;
					mLeftHeight = this.mMeasuredHeight - tvd.lines * lineHeight - 8; 
				*/	
				}
			}else if(childView.getContentDescription() == "img"){
				ImageView iv = (ImageView) childView;
				BitmapDrawable id = (BitmapDrawable) iv.getDrawable();
				//Bitmap id = iv.getDrawingCache();
				final int imageWidth = id.getBitmap().getWidth();
				final int imageHeight= id.getBitmap().getHeight();
				int scaleWidth = 0;
				int scaleHeight= 0;
				if(imageWidth > this.mMeasureWidth || imageHeight > this.mMeasuredHeight){
					if(imageWidth > imageHeight){
						scaleWidth = this.mMeasureWidth;
						scaleHeight= scaleWidth * imageHeight / imageWidth;
					}else{
						scaleHeight = this.mMeasuredHeight;
						scaleWidth = scaleHeight * imageWidth / imageHeight;
					}
				}else {
					scaleWidth = imageWidth;
					scaleHeight = imageHeight;
				}
				
				if(mLeftHeight < scaleHeight){
					childLeft = childWidth + childLeft;
					this.mPageCount++;
					iv.layout(childLeft, 0, childLeft+childWidth, scaleHeight);
					mLeftHeight = this.mMeasuredHeight - scaleHeight;
				}else{
					iv.layout(childLeft, this.mMeasuredHeight-mLeftHeight, childLeft+childWidth,  this.mMeasuredHeight - mLeftHeight + scaleHeight);
					mLeftHeight = mLeftHeight - scaleHeight;
				}
			}else if(childView.getContentDescription() == "h1"){
				TextView tv = (TextView)childView;
				if(mLeftHeight >= tv.getLineHeight() * tv.getLineCount()){
					childView.layout(childLeft, this.mMeasuredHeight - mLeftHeight,childWidth + childLeft, this.mMeasuredHeight - mLeftHeight +tv.getLineHeight() * tv.getLineCount());
					mLeftHeight = mLeftHeight -tv.getLineHeight() * tv.getLineCount()- 10;
				}else{
					this.mPageCount++;
					childLeft += childWidth;
					childView.layout(childLeft, 0, childLeft+childWidth, tv.getLineHeight() * tv.getLineCount());
					mLeftHeight = this.mMeasuredHeight - tv.getLineHeight() * tv.getLineCount()- 10;
				}
			}else if(childView.getContentDescription() == "h2"){
				TextView tv = (TextView)childView;
				if(mLeftHeight >= tv.getLineHeight() * tv.getLineCount()){
					childView.layout(childLeft, this.mMeasuredHeight - mLeftHeight,childWidth + childLeft, this.mMeasuredHeight - mLeftHeight +tv.getLineHeight() * tv.getLineCount());
					mLeftHeight = mLeftHeight -tv.getLineHeight() * tv.getLineCount()- 10;
				}else{
					this.mPageCount++;
					childLeft += childWidth;
					childView.layout(childLeft, 0, childLeft+childWidth, tv.getLineHeight() * tv.getLineCount());
					mLeftHeight = this.mMeasuredHeight - tv.getLineHeight() * tv.getLineCount()- 10;
				}
			}else if(childView.getContentDescription() == "h3"){
				TextView tv = (TextView)childView;
				if(mLeftHeight >= tv.getLineHeight() * tv.getLineCount()){
					childView.layout(childLeft, this.mMeasuredHeight - mLeftHeight,childWidth + childLeft, this.mMeasuredHeight - mLeftHeight +tv.getLineHeight() * tv.getLineCount());
					mLeftHeight = mLeftHeight -tv.getLineHeight() * tv.getLineCount()- 10;
				}else{
					this.mPageCount++;
					childLeft += childWidth;
					childView.layout(childLeft, 0, childLeft+childWidth, tv.getLineHeight() * tv.getLineCount());
					mLeftHeight = this.mMeasuredHeight - tv.getLineHeight() * tv.getLineCount()- 10;
				}
			}else if(childView.getContentDescription() == "nextpage"){
				this.mPageCount++;
				mLeftHeight = this.mMeasuredHeight;
				childLeft += childWidth;
			}
		}
		//((SReaderBookViewActivity)mContext).dismissDialog(SReaderBookViewActivity.DIALOG_PROGRESS);
	}

	private List<TextViewDivider> divideIntoParas(final TextView oldTextView,int leftHeight,final int maxWidth){
		List<TextViewDivider> list = new ArrayList<TextViewDivider>();
		
		final int leftLine = leftHeight / oldTextView.getLineHeight();
		final int maxLine  = this.mMeasuredHeight / oldTextView.getLineHeight();
		
		LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		String newStr1 = "";
		String oldStr  = (String) oldTextView.getText();
		TextPaint tp   = oldTextView.getPaint();
		
		//int breakAt = linebreakWithLines(oldStr, tp, maxWidth, leftLine);
		Layout textViewLayout = oldTextView.getLayout();
		int end = textViewLayout.getLineEnd(leftLine);
		newStr1 = oldStr.substring(0, end);
		oldStr  = oldStr.substring(end,oldStr.length());
		
		if(newStr1.length() == 0){
			//list.add(null);
			TextView tv1 = (TextView) inflater.inflate(R.layout.para_text, null);
			tv1.setText("");
			TextViewDivider tvd = new TextViewDivider();
			tvd.tv = tv1;
			tvd.lines = 0;
			list.add(tvd);
		}else{
			TextView tv1 = (TextView) inflater.inflate(R.layout.para_text, null);
			tv1.setText(newStr1);
			TextViewDivider tvd = new TextViewDivider();
			tvd.tv = tv1;
			tvd.lines = leftLine;
			list.add(tvd);
		}
		
		List<Integer> breakPos = linebreak(oldStr,tp,maxWidth);
		final int pageSize = breakPos.size() / maxLine ;
		if(breakPos.size() == 0 || pageSize == 0) {
			TextView tv = (TextView)inflater.inflate(R.layout.para_text, null);
			tv.setText(oldStr);
			TextViewDivider tvd = new TextViewDivider();
			tvd.tv = tv;
			tvd.lines = calcLines(oldStr,tp,maxWidth);
			list.add(tvd);
			return list;
		}
		
		int start = 0;
		for(int i = 1 ; i <= pageSize; i++){
			TextViewDivider tvd = new TextViewDivider();
			tvd.tv = (TextView)inflater.inflate(R.layout.para_text, null);
			String content = oldStr.substring(start, breakPos.get(maxLine * i));
			tvd.tv.setText(content);
			tvd.lines = maxLine;
			list.add(tvd);
			start = maxLine * i + 1;
		}
		
		TextViewDivider tvd = new TextViewDivider();
		tvd.tv = (TextView)inflater.inflate(R.layout.para_text, null);
		String content = oldStr.substring(start, oldStr.length());
		tvd.tv.setText(content);
		tvd.lines = calcLines(content,tp, maxWidth);
		list.add(tvd);
		return list;
	}
	
	private List<Integer> linebreak(String str, TextPaint textPaint, final int width){
		List<Integer> breakPos = new ArrayList<Integer>();
		int start = 0;
		while(true){
			int breakAt = textPaint.breakText(str, start, str.length(), true, width, null);
			if(breakAt == (str.length()-start)){
				break;
			}else{
				breakPos.add(breakAt + start);
				start = breakAt + start;
			}
		}
		
		return breakPos;
	}
	
	private int linebreakWithLines(String str, TextPaint textPaint, final int width, final int lines){
		if(lines == 0 || (str != null && str.length() == 0)) return 0;
		int start = 0;
		for(int i = 0 ; i < lines; i++){
			int breakAt = textPaint.breakText(str, start, str.length(), true, width, null);
			if(breakAt == (str.length() - start)){
				break;
			}else{
				start = breakAt + start ;
			}
		}
		return start;
	}
	
	private int calcLines(String str, TextPaint tp , final int width){
		int lineCount = 0;
		int start = 0 ;
		int end   = str.length();
		int measureCharNum = 0;
		while(end > start){
			measureCharNum = tp.breakText(str, start, end, true ,width, null);
			start = start + measureCharNum;
			lineCount ++;
		}
		return lineCount;
	}
	
    @Override  
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {   
    	Log.e(TAG, "onMeasure");
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        this.widthMeasureSpec = widthMeasureSpec;
        this.heightMeasureSpec = heightMeasureSpec;
  
        final int width = MeasureSpec.getSize(widthMeasureSpec);
        final int height = MeasureSpec.getSize(heightMeasureSpec);
        this.mMeasuredHeight = height;
        this.mMeasureWidth   = width;

        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);   
        if (widthMode != MeasureSpec.EXACTLY) {   
            throw new IllegalStateException("ScrollLayout only canmCurScreen run at EXACTLY mode!"); 
        }   
  
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);   
        if (heightMode != MeasureSpec.EXACTLY) {   
            throw new IllegalStateException("ScrollLayout only can run at EXACTLY mode!");
        }   
        
        // The children are given the same width and height as the scrollLayout   
        final int count = getChildCount();   
        for (int i = 0; i < count; i++) {   
            getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);   
        }   
        // Log.e(TAG, "moving to screen "+mCurScreen);   
        scrollTo(mCurScreen * width, 0);         
    }  
    
    /**
     * According to the position of current layout
     * scroll to the destination page.
     */
    public void snapToDestination() {
    	final int screenWidth = getWidth();
    	final int destScreen = (getScrollX()+ screenWidth/2)/screenWidth;
    	snapToScreen(destScreen);
    }
    
    public void snapToScreen(int whichScreen) {
    	// get the valid layout page
    	if(whichScreen > this.mPageCount){
    		Log.v(TAG, "next chapter");
    		if(this.mCurChapter < this.mChapterCount){
    			this.myRemoveAllView();
    			setChapterWithNum(this.mCurChapter+1);
    			this.mPageCount = 0;
    			measure(widthMeasureSpec, heightMeasureSpec);
	    		onLayout(true, 0, 0, this.mMeasureWidth, this.mMeasuredHeight);
	    		mCurScreen = 0;
	    		//snapToScreen(mCurScreen);
	    		//mScroller.startScroll(0, 0, 0, 0);
	    		invalidate();
	    		this.mCurChapter++;
	    		this.mCurPage = 0;
	    	//	if(this.pageChangeListener!=null) this.pageChangeListener.onNextPage();
    		}else{
    			whichScreen = Math.max(0, Math.min(whichScreen, /*getChildCount()-1*/this.mPageCount));
    	    	if (getScrollX() != (whichScreen*getWidth())) {
    	    		
    	    		final int delta = whichScreen*getWidth()-getScrollX();
    	    		mScroller.startScroll(getScrollX(), 0, 
    	    				delta, 0, Math.abs(delta)*2);
    	    		mCurScreen = whichScreen;
    	    		invalidate();		// Redraw the layout
    	    	}
    		}
    	}else if(whichScreen == -1){
    		if(this.mCurChapter > 0){
    			this.myRemoveAllView();
    			setChapterWithNum(this.mCurChapter-1);
    			this.mPageCount = 0;
    			measure(widthMeasureSpec, heightMeasureSpec);
	    		onLayout(true, 0, 0, this.mMeasureWidth, this.mMeasuredHeight);
	    		mCurScreen = this.mPageCount;
	    		//final int delta = mCurScreen*getWidth();
	    		//snapToScreen(mCurScreen);
	    		//mScroller.startScroll(0, 0, delta, 0);
	    		invalidate();
	    		this.mCurChapter--;
	    		this.mCurPage = mCurScreen;
	    	//	if(this.pageChangeListener != null) this.pageChangeListener.onPrevPage();
    		}else{
    			whichScreen = Math.max(0, Math.min(whichScreen, /*getChildCount()-1*/this.mPageCount));
    	    	if (getScrollX() != (whichScreen*getWidth())) {
    	    		
    	    		final int delta = whichScreen*getWidth()-getScrollX();
    	    		mScroller.startScroll(getScrollX(), 0, 
    	    				delta, 0, Math.abs(delta)*2);
    	    		mCurScreen = whichScreen;
    	    		invalidate();		// Redraw the layout
    	    	}
    		}
    	}else{
	    	whichScreen = Math.max(0, Math.min(whichScreen, /*getChildCount()-1*/this.mPageCount));
	    	if (getScrollX() != (whichScreen*getWidth())) {
	    		
	    		final int delta = whichScreen*getWidth()-getScrollX();
	    		mScroller.startScroll(getScrollX(), 0, 
	    				delta, 0, Math.abs(delta)*2);
	    		mCurScreen = whichScreen;
	    		mCurPage   = mCurScreen;
	    		invalidate();		// Redraw the layout
	    	/*	if(this.pageChangeListener != null){
	    			if(delta > 0) this.pageChangeListener.onNextPage();
	    			else this.pageChangeListener.onPrevPage();
	    		}*/
	    	}
    	}
    	if(this.pageChangeListener != null){
    		this.pageChangeListener.onPage(mCurPage+1);
    	}
    }
    
    private void setChapterWithNum(int num) {
		// TODO Auto-generated method stub
    	List<Paragraph> chapter = book.getChapterWithNum(num);
    	addChildViews(chapter);
	}
    
    private void addChildViews(List<Paragraph> chapter){
    	LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if(chapter == null) return ;
		else {
			for(Paragraph para:chapter){
				switch(para.type){
				case text:
					TextView tv = (TextView) inflater.inflate(R.layout.para_text, null);
					tv.setText((CharSequence) para.para);
					tv.setContentDescription("text");
					this.addView(tv);
					break;
				case img:
					ImageView iv = (ImageView) inflater.inflate(R.layout.image_para, null);
					
					iv.setImageBitmap( (Bitmap) para.para);
					iv.setContentDescription("img");
					this.addView(iv);
					break;
				case h1:
					TextView h1 = (TextView) inflater.inflate(R.layout.h1_text, null);
					h1.setText((CharSequence) para.para);
					h1.setContentDescription("h1");
					this.addView(h1);
					break;
				case h2:
					TextView h2 = (TextView) inflater.inflate(R.layout.h2_text, null);
					h2.setText((CharSequence) para.para);
					h2.setContentDescription("h2");
					this.addView(h2);
					break;
				case h3:
					TextView h3 = (TextView) inflater.inflate(R.layout.h3_text, null);
					h3.setText((CharSequence) para.para);
					h3.setContentDescription("h3");
					this.addView(h3);
					break;
				default:
					break;
				}
			}
		}
    }

	private boolean setNextChapter() {
		// TODO Auto-generated method stub
    	List<Paragraph> chapter = book.getNextChapter();
    	addChildViews(chapter);
		return true;
	}

	public void setToScreen(int whichScreen) {
    	whichScreen = Math.max(0, Math.min(whichScreen, /*getChildCount()-1*/this.mPageCount));
    	mCurScreen = whichScreen;
    	scrollTo(whichScreen*getWidth(), 0);
    }
    
    public int getCurScreen() {
    	return mCurScreen;
    }
    
    
	@Override
	public void computeScroll() {
		// TODO Auto-generated method stub
		if (mScroller.computeScrollOffset()) {
			scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
			postInvalidate();
		}
	}
	
	boolean isMove = false;

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		
		if (mVelocityTracker == null) {
			mVelocityTracker = VelocityTracker.obtain();
		}
		mVelocityTracker.addMovement(event);
		
		final int action = event.getAction();
		final float x = event.getX();
		final float y = event.getY();
		
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			Log.e(TAG, "event down!");
			if (!mScroller.isFinished()){
				mScroller.abortAnimation();
			}
			mLastMotionX = x;
			break;
			
		case MotionEvent.ACTION_MOVE:
			int deltaX = (int)(mLastMotionX - x);
			mLastMotionX = x;
			isMove = true;
			
            scrollBy(deltaX, 0);
			break;
			
		case MotionEvent.ACTION_UP:
			Log.e(TAG, "event : up");   
            // if (mTouchState == TOUCH_STATE_SCROLLING) {   
            final VelocityTracker velocityTracker = mVelocityTracker;   
            velocityTracker.computeCurrentVelocity(1000);   
            int velocityX = (int) velocityTracker.getXVelocity();   
            if(isMove == false){
            	if(x > 0 && x < this.mMeasureWidth/4) {
            		//goto prepage
            		snapToScreen(mCurScreen - 1);
            	}else if(x >this.mMeasureWidth / 4 && x<this.mMeasureWidth * 3/4){
            		//hide the access
            		if(this.middleClickListener != null) this.middleClickListener.onMinddleClick();
            	}else{
            		//goto nextpage
            		snapToScreen(mCurScreen + 1);
            	}
            }else{
				Log.e(TAG, "velocityX:" + velocityX);
				if (velocityX > SNAP_VELOCITY && mCurScreen >= 0) {
					// Fling enough to move left
					Log.e(TAG, "snap left");
					snapToScreen(mCurScreen - 1);
				} else if (velocityX < -SNAP_VELOCITY
						&& mCurScreen < this.mPageCount - 1) {
					// Fling enough to move right
					Log.e(TAG, "snap right");
					snapToScreen(mCurScreen + 1);
				} else {
					snapToDestination();
				}

				if (mVelocityTracker != null) {
					mVelocityTracker.recycle();
					mVelocityTracker = null;
				}

				// }
			}
            isMove = false;
            mTouchState = TOUCH_STATE_REST;   
			break;
		case MotionEvent.ACTION_CANCEL:
			mTouchState = TOUCH_STATE_REST;
			break;
		}
		
		return true;
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		Log.e(TAG, "onInterceptTouchEvent-slop:"+mTouchSlop);
		
		final int action = ev.getAction();
		if ((action == MotionEvent.ACTION_MOVE) && 
				(mTouchState != TOUCH_STATE_REST)) {
			return true;
		}
		
		final float x = ev.getX();
		final float y = ev.getY();
		
		switch (action) {
		case MotionEvent.ACTION_MOVE:
			final int xDiff = (int)Math.abs(mLastMotionX-x);
			if (xDiff>mTouchSlop) {
				mTouchState = TOUCH_STATE_SCROLLING;
				
			}
			break;
			
		case MotionEvent.ACTION_DOWN:
			mLastMotionX = x;
			mLastMotionY = y;
			mTouchState = mScroller.isFinished()? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
			break;
			
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP:
			mTouchState = TOUCH_STATE_REST;
			break;
		}
		return mTouchState != TOUCH_STATE_REST;
	}
	
	private Book book = null;

	public void setBookResource(Book book) {
		// TODO Auto-generated method stub
		this.book = book;
		this.mCurChapter = book.getCurChapter();
		this.mChapterCount = book.getChapterSize()-1;
		this.mCurPage    = book.getCurPage();
		this.setChapterWithNum(this.mCurChapter);
		this.mCurScreen  = this.mCurPage;
	}
	
	class TextViewDivider{
		TextView tv;
		int      lines;
	}

	public void jumpToChapter(int num, int i) {
		// TODO Auto-generated method stub
		this.mCurChapter = num;
		this.mCurPage = 0;
		this.mPageCount = 0;
		this.myRemoveAllView();
		this.setChapterWithNum(num);
		this.mCurScreen = this.mCurPage;
		measure(widthMeasureSpec, heightMeasureSpec);
		onLayout(true, 0, 0, this.mMeasureWidth, this.mMeasuredHeight);
		if(this.pageChangeListener != null) this.pageChangeListener.onPage(this.mCurPage+1);
	}

	private void myRemoveAllView() {
		// TODO Auto-generated method stub
		this.removeAllViewsInLayout();
	}
}
